package com.eoner.baselibrary.widget;

import android.animation.Keyframe;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.text.SpannableString;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;
import com.eoner.baselibrary.R;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

/**
 * 对 support Design 包中的TabLayout包装
 */
public class PurchaseTabLayout extends FrameLayout {
    private TabLayout mTabLayout;
    private List<String> mTabList;
    private List<View> mCustomViewList;
    private int mTabMode;
    private int mTabTextSize;

    Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(nopeAnimator != null && nopeAnimator.isRunning()){
                nopeAnimator.end();
            }
        }
    };

    public PurchaseTabLayout(@NonNull Context context) {
        super(context);
        init(context, null);
    }

    public PurchaseTabLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public PurchaseTabLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public PurchaseTabLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(context, attrs);
    }

    private void readAttr(Context context, AttributeSet attrs) {
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.EnhanceTabLayout);
        mTabTextSize = typedArray.getDimensionPixelSize(R.styleable.EnhanceTabLayout_tabTextSize, 14);
        mTabMode = typedArray.getInt(R.styleable.EnhanceTabLayout_tab_Mode, 1);
        typedArray.recycle();
    }

    private void init(Context context, AttributeSet attrs) {
        readAttr(context, attrs);

        mTabList = new ArrayList<>();
        mCustomViewList = new ArrayList<>();
        View view = LayoutInflater.from(getContext()).inflate(R.layout.purchase_tab_layout, this, true);
        mTabLayout = (TabLayout) view.findViewById(R.id.enhance_tab_view);

        // 添加属性
        mTabLayout.setTabMode(mTabMode == 1 ? TabLayout.MODE_FIXED : TabLayout.MODE_SCROLLABLE);
        mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                // onTabItemSelected(tab.getPosition());
                // Tab 选中之后，改变各个Tab的状态
                for (int i = 0; i < mTabLayout.getTabCount(); i++) {
                    View view = mTabLayout.getTabAt(i).getCustomView();
                    if (view == null) {
                        return;
                    }
                    TextView text = (TextView) view.findViewById(R.id.tab_item_text);
                    TextView tvSubText = (TextView) view.findViewById(R.id.tab_item_sub_text);
                    View tabItem = view.findViewById(R.id.tab_item);
                    if (i == tab.getPosition()) { // 选中状态
                        if (i == 0){
                            tabItem.setBackgroundResource(R.mipmap.tab_first_purchase_selected);
                        }else {
                            tabItem.setBackgroundResource(R.mipmap.tab_last_purchase_selected);
                        }
                        startLeftAndRightShake(tabItem);
                        mHandler.sendEmptyMessageDelayed(0,200);
                        text.setTextSize(16);
                        tvSubText.setTextSize(12);
                    } else {// 未选中状态
                        if (i == 0){
                            tabItem.setBackgroundResource(R.mipmap.tab_first_purchase_unselect);
                        }else {
                            tabItem.setBackgroundResource(R.mipmap.tab_last_purchase_unselect);
                        }
                        text.setTextSize(15);
                        tvSubText.setTextSize(11);
                    }
                }

            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    ObjectAnimator nopeAnimator;
    private void startLeftAndRightShake(View view) {
        //左右移动
        nopeAnimator = nope2(view);
        nopeAnimator.setRepeatCount(ValueAnimator.INFINITE);
        nopeAnimator.start();
    }

    private  ObjectAnimator nope2(View view) {
        int delta = 10;
        PropertyValuesHolder pvhTranslateX = PropertyValuesHolder.ofKeyframe(View.TRANSLATION_Y,
                Keyframe.ofFloat(0f, 0),
                Keyframe.ofFloat(.10f, -delta),
                Keyframe.ofFloat(.26f, delta),
                Keyframe.ofFloat(1f, 0f)
        );
        return ObjectAnimator.ofPropertyValuesHolder(view, pvhTranslateX).
                setDuration(200);
    }

    public List<View> getCustomViewList() {
        return mCustomViewList;
    }

    public void addOnTabSelectedListener(TabLayout.OnTabSelectedListener onTabSelectedListener) {
        mTabLayout.addOnTabSelectedListener(onTabSelectedListener);
    }

    /**
     * 与TabLayout 联动
     *
     * @param viewPager
     */
    public void setupWithViewPager(@Nullable ViewPager viewPager) {
        mTabLayout.addOnTabSelectedListener(new ViewPagerOnTabSelectedListener(viewPager, this));
    }


    /**
     * retrive TabLayout Instance
     *
     * @return
     */
    public TabLayout getTabLayout() {
        return mTabLayout;
    }

    /**
     * 添加tab
     *
     * @param tab
     */
    public void addTab(String tab,String sbTab, boolean selected) {
        mTabList.add(tab);
        View customView = getTabView(getContext(), tab, sbTab, mTabTextSize, selected);
        mCustomViewList.add(customView);
        mTabLayout.addTab(mTabLayout.newTab().setCustomView(customView));
    }

    /**
     * 添加tab
     */
    public void updateSbTab(SpannableString sbTab) {
        View customView = mTabLayout.getTabAt(0).getCustomView();
        TextView tvSubText = (TextView) customView.findViewById(R.id.tab_item_sub_text);
        tvSubText.setText(sbTab);
    }

    public static class ViewPagerOnTabSelectedListener implements TabLayout.OnTabSelectedListener {

        private final ViewPager mViewPager;
        private final WeakReference<PurchaseTabLayout> mTabLayoutRef;

        public ViewPagerOnTabSelectedListener(ViewPager viewPager, PurchaseTabLayout enhanceTabLayout) {
            mViewPager = viewPager;
            mTabLayoutRef = new WeakReference<PurchaseTabLayout>(enhanceTabLayout);
        }

        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            mViewPager.setCurrentItem(tab.getPosition());
            PurchaseTabLayout mTabLayout = mTabLayoutRef.get();
            if (mTabLayoutRef != null) {
                List<View> customViewList = mTabLayout.getCustomViewList();
                if (customViewList == null || customViewList.size() == 0) {
                    return;
                }
                for (int i = 0; i < customViewList.size(); i++) {
                    View view = customViewList.get(i);
                    if (view == null) {
                        return;
                    }
                    TextView text = (TextView) view.findViewById(R.id.tab_item_text);
                    TextView tvSubText = (TextView) view.findViewById(R.id.tab_item_sub_text);
                    View tabItem = view.findViewById(R.id.tab_item);
                    if (i == tab.getPosition()) { // 选中状态
                        if (i == 0){
                            tabItem.setBackgroundResource(R.mipmap.tab_first_purchase_selected);
                        }else {
                            tabItem.setBackgroundResource(R.mipmap.tab_last_purchase_selected);
                        }
                        text.setTextSize(16);
                        tvSubText.setTextSize(12);
                    } else {// 未选中状态
                        if (i == 0){
                            tabItem.setBackgroundResource(R.mipmap.tab_first_purchase_unselect);
                        }else {
                            tabItem.setBackgroundResource(R.mipmap.tab_last_purchase_unselect);
                        }
                        text.setTextSize(15);
                        tvSubText.setTextSize(11);
                    }
                }
            }

        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {
            // No-op
        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {
            // No-op
        }
    }

    /**
     * 获取Tab 显示的内容
     *
     * @param context
     * @param
     * @return
     */
    public View getTabView(Context context, String text,String subText,int textSize, boolean selected) {
        View view = LayoutInflater.from(context).inflate(R.layout.purchase_tab_item_layout, null);
        TextView tvTabText = (TextView) view.findViewById(R.id.tab_item_text);
        TextView tvSubText = (TextView) view.findViewById(R.id.tab_item_sub_text);
        tvTabText.setTextColor(Color.parseColor("#FF5000"));
        tvSubText.setTextColor(Color.parseColor("#525866"));
        tvTabText.setText(text);
        tvSubText.setText(subText);
        if (selected){
            view.setBackgroundResource(R.mipmap.tab_first_purchase_selected);
        }else {
            view.setBackgroundResource(R.mipmap.tab_last_purchase_unselect);
        }
        return view;
    }
}

